package cn.didi.feidi.androidorder.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.Map;

import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.api.ErrorEvent;
import cn.didi.feidi.androidorder.assembly.CommomDialog;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.manager.AppManager;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.model.AppInfo;
import cn.didi.feidi.androidorder.model.LoginReturnResultByUser;
import cn.didi.feidi.androidorder.service.DownloadApkService;
import cn.didi.feidi.androidorder.util.PackageUtil;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by king on 2017/8/25.
 */

@RuntimePermissions
public class StartAppActivity extends FeidiBaseActivity {

    protected static final String TAG = "StartAppActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout_start_app);
    }

    /**
     * 设置已经引导过了，下次启动不用再次引导
     */
    private void setGuided() {
        AppManager.putFirstInAppFlag(false);
    }

    /**
     * 跳转到主页
     */
    private void goHome() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        overridePendingTransition(R.anim.anim_out, R.anim.anim_in);// 淡出淡入动画效果
        finish();
    }

    /**
     * 跳转到登录界面
     */
    private void goLogin() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        overridePendingTransition(R.anim.anim_out, R.anim.anim_in);// 淡出淡入动画效果
        finish();
    }

    /**
     * 跳转到导航页
     */
    private void goGuide() {
        ////  : 2017/7/24 创建导航页
        goLogin();
//        Intent intent = new Intent(this, MainActivity.class);
//        startActivity(intent);
//        finish();
    }

    @Override
    protected int setFeidiActionBarId() {
        return 0;
    }

    @Override
    protected void initViews() {
    }

    /**
     * 1、访问服务器，检测更新
     * 2、分析版本信息
     * 3、检测是否第一次登录
     * 4、更新个人信息
     */
    @Override
    protected void initData() {
        StartAppActivityPermissionsDispatcher.getPermissionWithCheck(this);
        checkVersion();
    }

    /**
     * 判断程序与第几次运行，如果是第一次运行则跳转到引导界面，否则跳转到主界面
     */
    private void checkIsFirstInApp() {
        if (!AppManager.getFirstInAppFlag()) {
            InitAppData();
        } else {
            setGuided();
            goGuide();
        }
    }

    /**
     * 访问服务器，检测更新
     * 成功：分析版本信息，并处理
     * 失败：不分析版本信息，进行下一步
     */
    private void checkVersion() {
        String version = PackageUtil.getVersionName(this);
        Map<String, String> data = new HashMap<String, String>();
        data.put("version", version);
        executeRequest(new AppActionRequest<AppInfo>(Api.CHECK_APP_VERSION, data, new TypeToken<ApiResponse<AppInfo>>() {
        }.getType(), new ActionCallbackListener<AppInfo>() {
            @Override
            public void onSuccess(String message, AppInfo data) {
                if (data == null) {//获取异常，数据为空
                    checkIsFirstInApp();
                    return;
                }
                analysisAppInfo(data);
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                makeToast(message);
                checkIsFirstInApp();
            }
        }));
    }

    /**
     * 分析版本信息，并处理
     *
     *
     * @param appInfo
     */
    private void analysisAppInfo(AppInfo appInfo) {
        Log.d(TAG, "chaoking-appInfo 服务器最新版本" + appInfo.getVersion());
        AppManager.putAppInfo(appInfo);//保存新app信息

        if (PackageUtil.getVersionName(this).compareTo(appInfo.getVersion()) < 0) {// 非强制更新提示
            if (appInfo.isForce()) {
                // 如果是强制更新,则自动下载，不进行提示
                downloadAPK();
                return;
            } else {
                showUpdateDialog(appInfo);
            }
        } else {// 无更新提示
            checkIsFirstInApp();
        }
    }
    /**
     * 显示更新提示
     *
     * @param appInfo
     */
    private void showUpdateDialog(AppInfo appInfo) {
        new CommomDialog(this, R.style.dialog, appInfo.getClientDesc(), new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    Log.d(TAG,"现在更新");
                    downloadAPK();
                    checkIsFirstInApp();
                    dialog.dismiss();
                } else {
                    checkIsFirstInApp();
                    Log.d(TAG,"待会更新");
                    dialog.dismiss();
                }
            }
        }, false, false).setTitle("版本更新").setNegativeButton("待会更新").setPositiveButton("现在更新").show();
    }

    private void downloadAPK() {
        startService(new Intent(this, DownloadApkService.class));
    }

    /**
     * 初始化app信息
     */
    private void InitAppData() {
        if (UserManager.isBingAccount()) {
            Map<String, String> data = new HashMap<String, String>();
            data.put("uid", UserManager.getUserId());
            data.put("token", UserManager.getToken());
            executeRequest(new AppActionRequest<LoginReturnResultByUser>(Api.LOGIN_PASSWORD_FREE, data, new TypeToken<ApiResponse<LoginReturnResultByUser>>() {
            }.getType(), new ActionCallbackListener<LoginReturnResultByUser>() {
                @Override
                public void onSuccess(String message, LoginReturnResultByUser data) {
                    if (data != null) {
                        ////  : 2017/7/18 建立长连接
                        Log.d(TAG, "登陆成功: " + data.getLoginInfo().getToken() + " : " + data.getLoginInfo().getUid());
                        //  : 2017/7/19 登陆成功，跳到下一个activity
                        //保存用户必要信息

                        //保存用户必要信息
                        UserManager.setUserId(data.getLoginInfo().getUid());
                        UserManager.setToken(data.getLoginInfo().getToken());
                        UserManager.setPhone(data.getUser().getPhoneNumber());

                        UserManager.setName(data.getUser().getName());
                        UserManager.setHeadPortrait(data.getUser().getPortraitUrl());
                        UserManager.setFeidiAccount(data.getUser().getFeidiAccount());
                        UserManager.setFeidiAccountStatus(data.getUser().getFeidiAccountStatus());

                        if (data.getUser().getTouchDeliverId() != null&&!"".equals(data.getUser().getTouchDeliverId()))
                            UserManager.setWaterDelverId(data.getUser().getTouchDeliverId());
                        //判断是否设置支付密码
                        if (data.getUser().getPayPwd().equals("0")){
                            UserManager.setPayPassword(true);
                        }else{
                            UserManager.setPayPassword(false);
                        }

                        userLogin();
                        goHome();
                    } else {
                        makeToast("success" + message);
                        Log.d(TAG, message);
                    }
                }

                @Override
                public void onFailure(int errorEvent, String message) {
                    switch (errorEvent) {
                        case ErrorEvent.WRONG_REMEMBER_ME:
                            makeToast("登陆认证失败,请重新登陆");
                            //免密码登录失败，清空信息
                            UserManager.clearBingAccountInfo();
                            break;
                        default:
                            makeToast("未知错误");
                            //免密码登录失败，清空信息
                            UserManager.clearBingAccountInfo();
                            break;
                    }
                    goLogin();
                }
            }).setEmergency(true));
        } else {
            goLogin();
        }
    }

    @Override
    protected void addListener() {
    }

    @NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    public void getPermission() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
